package pt.compflow.client.api;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.representation.EmptyRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Post;

import pt.compflow.Context;
import pt.compflow.flowontology.model.FlowOntologyModel;
import pt.compflow.flowontology.model.Job;
import pt.compflow.flowontology.model.Person;
import pt.compflow.storage.TripleStoreConnection;

public class JobFromTemplateResource extends APIBaseResource {

//	private static final Logger LOG = LoggerFactory.getLogger(PersonResource.class);
	
		
	@Post("json")
	public Representation create(String json) throws JSONException, IOException {
						
		JSONObject request = new JSONObject(json);
		
		if(!request.has("template") || request.getString("template").length() <= 1) {
			setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
			return new EmptyRepresentation();
		}
		
		Context context = getCompFlowContext();
		TripleStoreConnection store = context.getStoreConnection();
		store.openStore();
		
		FlowOntologyModel model = store.connectModel();
						
		Person p = getPerson(model, null);
		if(p == null) {
			setStatus(Status.CLIENT_ERROR_UNAUTHORIZED);
			store.closeStore();
			return new EmptyRepresentation();
		}
		
		//String jobTemplateId = context.getJobTemplateManager().createJobTemplate(p, request);
		Job job = context.getJobController().loadAndStartJob(p.getURI(), request.getString("template"));
		
		setStatus(Status.SUCCESS_OK);
		
		StringRepresentation sr = new StringRepresentation(job.getLocalName(), MediaType.TEXT_PLAIN);
		
		store.closeStore();
		
		return sr;
	}

}
